package com.csh.subject.infra.basic.utils;

import com.alibaba.druid.filter.config.ConfigTools;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

/**
 * 基于druid配置文件数据库密码加密util
 */
public class DruidEncryptUtil {
    private static String publicKey;

    private static String privateKey;

    static {
        try {
            String[] keyPair = ConfigTools.genKeyPair(512);
            privateKey = keyPair[0];
            System.out.println("私钥privateKey为:" + privateKey);
            publicKey = keyPair[1];
            System.out.println("公钥publicKey为:" + publicKey);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (NoSuchProviderException e) {
            throw new RuntimeException(e);
        }
    }

    //加密方法，传入原始密码，用私钥加密
    public static String encrypt(String plainText) throws Exception {
        String encryptText = ConfigTools.encrypt(privateKey, plainText);
//        System.out.println("encryptText:" + encryptText);
        return encryptText;
    }
    //解密方法，传入加密后的密码，用公钥解密
    public static String decrypt(String encryptText) throws Exception {
        String decryptText = ConfigTools.decrypt(publicKey, encryptText);
        System.out.println("decryptText:" + decryptText);
        return decryptText;
    }

    public static void main(String[] args) throws Exception {
        //调用加密方法，传入原始密码
        String encryptText = encrypt("Csh1Q2W#E");
        System.out.println("加密后:" + encryptText);
    }
}
